<script setup lang="ts">
import { Graph } from '@antv/x6'
import { ElButton } from 'element-plus'

const container = ref<HTMLDivElement>()

const graph = ref<Graph>()

Graph.registerNode(
  'custom-tools-node',
  {
    inherit: 'rect',
    width: 100,
    height: 40,
    attrs: {
      body: {
        stroke: '#8f8f8f',
        strokeWidth: 1,
        fill: '#fff',
        rx: 6,
        ry: 6,
      },
    },
  },
  true,
)

onMounted(() => {
  const graph = new Graph({
    container: container.value,
    background: {
      color: '#F2F7FA',
    },
  })

  const source = graph.addNode({
    shape: 'custom-tools-node',
    x: 40,
    y: 40,
    label: 'Source',
  })

  const target = graph.addNode({
    shape: 'custom-tools-node',
    x: 160,
    y: 240,
    label: 'Target',
  })

  graph.addEdge({
    source,
    target,
    vertices: [
      { x: 90, y: 160 },
      { x: 210, y: 160 },
    ],
    attrs: {
      line: {
        stroke: '#8f8f8f',
        strokeWidth: 1,
      },
    },
  })

  graph.on('cell:mouseenter', ({ cell }) => {
    if (cell.isNode()) {
      cell.addTools([
        {
          name: 'boundary',
          args: {
            attrs: {
              'fill': '#7c68fc',
              'stroke': '#333',
              'stroke-width': 1,
              'fill-opacity': 0.2,
            },
          },
        },
        {
          name: 'button-remove',
          args: {
            x: 0,
            y: 0,
            offset: { x: 10, y: 10 },
          },
        },
      ])
    }
    else {
      cell.addTools(['vertices', 'segments'])
    }
  })

  graph.on('cell:mouseleave', ({ cell }) => {
    cell.removeTools()
  })
})

function getJson() {
  const value = graph.value!.toJSON()

  console.log(value)
}
</script>

<template>
  <div>
    <div className="validate-app">
      <div ref="container" className="app-content" />
    </div>
    <ElButton @click="getJson">
      导出
    </ElButton>
  </div>
</template>

<style scoped lang="scss">
.validate-app {
  display: flex;
  width: 100%;
  padding: 0;
  font-family: sans-serif;

  .app-content {
    flex: 1;
    height: 280px;
    margin-right: 8px;
    margin-left: 8px;
    border-radius: 5px;
    box-shadow:
      0 12px 5px -10px rgb(0 0 0 / 10%),
      0 0 4px 0 rgb(0 0 0 / 10%);
  }
}
</style>
